package service

import (
	"fmt"
	"ruoyi-go/app/admin/model/monitor"
	"ruoyi-go/app/admin/model/tools"
	"ruoyi-go/pkg/mysql"
	"ruoyi-go/utils"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

var SysOperLogService = &serviceSysOperLog{}

type serviceSysOperLog struct{}

func (service serviceSysOperLog) AddSysOperLog(context *gin.Context, data string) {
	var operLog = monitor.SysOperLog{
		Title:      "错误日志",
		JsonResult: string(data),
		Status:     "1",
	}
	service.OperationLogAdd(operLog, context)
}

func (service serviceSysOperLog) SelectOperLogList(params tools.SearchTableDataParam) tools.TableDataInfo {
	var pageNum = params.PageNum
	var pageSize = params.PageSize
	offset := (pageNum - 1) * pageSize

	sysOperLog := params.Other.(monitor.SysOperLog)

	var rows []monitor.SysOperLog

	var beginTime = params.Params.BeginTime
	var endTime = params.Params.EndTime

	var total int64
	var db = mysql.MysqlDb().Model(&rows)

	var title = sysOperLog.Title
	if title != "" {
		db.Where("title like concat('%', ?, '%')", title)
	}
	var businessType = sysOperLog.BusinessType
	if businessType != "" {
		db.Where("business_type = ?", businessType)
	}

	/*目前没有用*/
	//var businessTypes = sysOperLog.BusinessTypes
	//if businessTypes != nil || len(businessTypes) > 0 {
	//	//db.Table("users").Where("id in ? ",[]int{1,2,3}).Find(&sysuser)
	//	db.Where("business_type in ?", businessTypes)
	//}

	var status = sysOperLog.Status
	if status != "" {
		db.Where("status = ?", status)
	}

	var oper_name = sysOperLog.OperName
	if oper_name != "" {
		db.Where("oper_name like concat('%', ?, '%')", oper_name)
	}
	var orderByColumn = params.OrderByColumn
	var isAsc = params.IsAsc

	if orderByColumn != "" {
		if isAsc == "ascending" {
			if orderByColumn == "operTime" {
				db.Order("oper_time DESC")
			}
			if orderByColumn == "operName" {
				db.Order("oper_name DESC")
			}
		}
		if isAsc == "descending" {
			if orderByColumn == "operTime" {
				db.Order("oper_time ASC")
			}
			if orderByColumn == "operName" {
				db.Order("oper_name ASC")
			}
		}
	}

	if beginTime != "" {
		//Loc, _ := time.LoadLocation("Asia/Shanghai")
		//startTime1, _ := time.ParseInLocation(constants.DateFormat, beginTime, Loc)
		//endTime = endTime + " 23:59:59"
		//endTime1, _ := time.ParseInLocation(constants.DateFormat, endTime, Loc)
		startTime1, endTime1 := utils.GetBeginAndEndTime(beginTime, endTime)
		//db.Where("oper_time >= ? and oper_time <= ?", startTime1, endTime1)
		db.Where("oper_time >= ?", startTime1)
		db.Where("oper_time <= ?", endTime1)
	}

	db.Order("oper_id desc")
	if err := db.Table(sysOperLog.TableName()).Count(&total).Error; err != nil {
		return tools.Fail()
	}
	if err := db.Limit(pageSize).Offset(offset).Find(&rows).Error; err != nil {
		return tools.Fail()
	}

	if rows == nil {
		return tools.Fail()
	} else {
		return tools.Success(rows, total)
	}
}

func (service serviceSysOperLog) DelectOperLog(operIds []int) {
	if err := mysql.MysqlDb().Where("oper_id in (?)", operIds).Delete(&monitor.SysOperLog{}).Error; err != nil {
		panic(err.Error())
	}
}

func (service serviceSysOperLog) ClearOperLog() {
	if err := mysql.MysqlDb().Exec("truncate table sys_oper_log").Error; err != nil {
		panic(err.Error())
	}
}

func (service serviceSysOperLog) OperationLogAdd(param monitor.SysOperLog, context *gin.Context) {
	userId, _ := context.Get("userId")
	if userId != nil {
		sysUser := SysUserService.FindUserById(userId)
		dept := SysDeptService.GetDeptInfo(strconv.Itoa(sysUser.DeptId))
		param.OperName = sysUser.UserName
		param.DeptName = dept.DeptName
		param.OperatorType = "1"
	}

	ip := utils.GetRemoteClientIp(context.Request)
	method := context.Request.Method
	param.Method = method
	param.RequestMethod = method

	if method == "GET" {
		param.BusinessType = monitor.BusinessTypeOther
	}
	if method == "POST" {
		param.BusinessType = monitor.BusinessTypeAdd
	}
	if method == "DEL" {
		param.BusinessType = monitor.BusinessTypeDel
	}
	if method == "PUT" {
		param.BusinessType = monitor.BusinessTypeEdit
	}

	param.OperUrl = context.Request.URL.Path

	param.OperIp = ip
	param.OperTime = time.Now()
	param.OperLocation = "" + utils.GetRealAddressByIP(ip)
	if err := mysql.MysqlDb().Model(&monitor.SysOperLog{}).Create(&param).Error; err != nil {
		fmt.Println(err)
	}
}
